const Koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const cors = require("@koa/cors");
const jwt = require("jwt-simple");

const app = new Koa();
const router = new Router();

app.use(bodyParser());
app.use(cors());
// 登陆
router.post("/login", async (ctx, next) => {
    let { username, password } = ctx.request.body;
    if (username == "admin" && password == "admin") {
        let token = jwt.encode({ username }, "ya"); // jwt-simple 实现
        ctx.body = {
            code: 200,
            data: {
                token,
                username,
            },
        };
    }
});
// 验证是否有权限
router.get("/validate", async (ctx, next) => {
    let Authorization = ctx.get("Authorization");
    if (Authorization) {
        let [, token] = Authorization.split(" ");
        try {
            let r = jwt.decode(token, "ya"); // jwt-simple 实现
            ctx.body = {
                code: 200,
                data: {
                    username: r,
                },
            };
        } catch {
            ctx.body = {
                code: 401,
                data: "token已失效",
            };
        }
    }
});

app.use(router.routes());
app.listen(3000);
